package com.xxx.car.biz.impl;

import com.xxx.car.biz.SmsService;
import com.xxx.car.cache.CarRedisTemplate;
import com.xxx.car.constants.CarConstants;
import com.xxx.car.constants.RedisConstants;
import com.xxx.car.entity.TbSmsContent;
import com.xxx.car.mapper.TbSmsContentMapper;
import com.xxx.car.redisCluster.utils.RedisKey;
import com.xxx.car.utils.RandomStringGenerator;
import com.xxx.common.sms.ChuangLanSms;
import com.xxx.common.sms.model.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by youxiaojia on 2017/6/13.
 */
@Service
public class SmsServiceImpl implements SmsService {
    private Logger logger = LoggerFactory.getLogger(getClass());

    private String REDIS_USER_PHONE_CODE_SET = "user_phone_code_set_";
    private String REDIS_USER_PHONE_MESSAGE_RESEND = "user_phone_message_resend";

    @Autowired
    TbSmsContentMapper tbSmsContentMapper;
    @Autowired
    CarRedisTemplate carRedisTemplate;

    @Override
    public Result sendMessageToPhone(String phone, String content) {
        TbSmsContent tbSmsContent = new TbSmsContent();
        tbSmsContent.setPhone(phone);
        tbSmsContent.setContent(content);
        tbSmsContent.setState(CarConstants.NO);
        this.tbSmsContentMapper.insertSelective(tbSmsContent);


        ChuangLanSms chuangLanSms = new ChuangLanSms();
        Result result = chuangLanSms.sendMsg(phone, content);

        if (result != null && result.isStatus()) {
            tbSmsContent.setId(tbSmsContent.getId());
            tbSmsContent.setState(CarConstants.YES);
            this.tbSmsContentMapper.updateByPrimaryKeySelective(tbSmsContent);
        }
        return result;
    }

    @Override
    public Result sendValidCodetToPhone(String phone, int resend, int exp) {
        //判断验证码是否过期.
        String code = (String)carRedisTemplate.get(RedisConstants.CAR_FAMILY_KEY + REDIS_USER_PHONE_MESSAGE_RESEND + phone);
        if (code == null) {
            code = RandomStringGenerator.getRandomDigitByLength(4);
            Result result = sendMessageToPhone(phone,  "您的验证码是："+code+"，"+(exp / 60)+"分钟内有效"); // TODO
            if (result.isStatus()) {
                carRedisTemplate.zadd(RedisConstants.CAR_FAMILY_KEY + REDIS_USER_PHONE_CODE_SET + phone, System.currentTimeMillis() + (exp * 1000), code);
                carRedisTemplate.save(RedisConstants.CAR_FAMILY_KEY + REDIS_USER_PHONE_MESSAGE_RESEND + phone, code, resend);
            }
            return result;
        } else {
            return Result.returnFail(Result.SMS_SEND_TOO_OFTEN);
        }
    }

    @Override
    public boolean verifyValidCode(String phone, String code) {
        RedisKey redisKey = new RedisKey(RedisConstants.CAR_FAMILY_KEY, REDIS_USER_PHONE_CODE_SET + phone);
        double score = carRedisTemplate.zScore(redisKey.getRedisKey(), code);
        if (score == 0.0) {
            logger.warn("verifyValidCode failed, code is not found, phone:" + phone + ",code:" + code);
            return false;
        }
        if ((long) score >= System.currentTimeMillis()) {
            carRedisTemplate.delteKey(redisKey.toString());
            carRedisTemplate.delteKey(new RedisKey(RedisConstants.CAR_FAMILY_KEY,REDIS_USER_PHONE_MESSAGE_RESEND + phone).toString());
            return true;
        }
        logger.warn("verifyValidCode failed, code expired,phone:" + phone + ",code:" + code + ",score:" + score);
        return false;
    }

    public static void main(String[] args){
        SmsServiceImpl smsServiceImpl = new SmsServiceImpl();
        smsServiceImpl.sendValidCodetToPhone("13802704472",60,120);
    }
}
